package org.jeecg.modules.power.timing.redisTask;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.common.exception.ChechDataAuthException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.v1.util.Const;
import org.jeecg.modules.power.device.service.IYlDeviceRecordsService;
import org.jeecg.modules.power.shop.service.IYlShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;


/**
 * Redis事件监听器
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Autowired
    private IYlDeviceRecordsService deviceRecordsService;
    @Autowired
    private IYlShopService shopService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 重写onMessage方法，当Redis中的Key过期时会执行该方法
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 过期的key
        String expireKey = message.toString();
        if(oConvertUtils.isEmpty(expireKey))return;
        /**
         * 门店7天无设备到期，处理自动进入公海
         */
        if( expireKey.startsWith("bank:empty:"))ExpireServiceSession( expireKey);

    }

    private void ExpireServiceSession(String expireKey) {
        /**
         * {@link Const.empty_shop_key = "bank:empty:shopId"}
         */
        String shopId = expireKey.split(":")[2];
        /**
         * 判定门店下是否还有设备未解绑
         */
        int count = deviceRecordsService.countShopDevice(shopId);
        if(count==0) {
            UpdateWrapper wrapper = new UpdateWrapper();
            wrapper.set("shop_status", Const.shop_status_4);
            wrapper.set("shop_bd", "");
            wrapper.set("bd_id", "");
            wrapper.set("org_id", "");
            wrapper.eq("id", shopId);
            shopService.update(wrapper);
        }
    }



}

